package io.zjw.testblelib.util;

import android.os.Environment;
import android.util.Log;

import com.yuanxu.ecg.L;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.nio.ByteBuffer;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FileUtil {

    static String storageState = null;

    public static FileWriter recordByte(String filePath){
        FileWriter writer = null;
        try {
            File file=new File(filePath);
            if (!file.exists()){
                file.getParentFile().mkdirs();
                if (file.createNewFile()){
                   writer = new FileWriter(filePath, true);
                }
            }
        }catch (Exception e){

        }
        return writer;
    }
    public static FileOutputStream outputStream(String filePath){
        FileOutputStream fos = null;
        try {
            File file=new File(filePath);
            if (!file.exists()){
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            fos = new FileOutputStream(file,true);
        }catch (Exception e){
        }
        return fos;
    }


    public static void addFile(String filePath, String requestUrlStr){
        File file = null;
        try {
            // getExternalStorageState 方法频繁调用会影响性能
            // 修改为只调用一次后解决卡顿问题，但无法及时获取状态变化，最好能做到对存储设备的状态变化的实时监听
            if (storageState == null) {
                storageState = Environment.getExternalStorageState();
            }
            if(storageState.equals(Environment.MEDIA_MOUNTED)){
                file=new File(filePath);
                if (!file.exists()){
                    file.getParentFile().mkdirs();
                    if (file.createNewFile()){
                        writeAppend(filePath,requestUrlStr);
                    }
                }else {
                    writeAppend(filePath,","+requestUrlStr);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static void writeAppend(String fileName, String requestUrlStr){

        FileWriter writer = null;
        try {
            writer = new FileWriter(fileName, true);
            writer.write(requestUrlStr);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void addFile(String filePath, byte requestUrlStr){
        File file = null;
        try {
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                file=new File(filePath);
                if (!file.exists()){
                    file.getParentFile().mkdirs();
                    if (file.createNewFile()){
                        writeAppend(filePath,requestUrlStr);
                    }
                }else {
                    //writeAppend(filePath,"\n"+requestUrlStr);
                    writeAppend(filePath,requestUrlStr);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    public static void addFile2(String filePath, String requestUrlStr,boolean flag){
//        File file = null;
//        try {
//            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//                file=new File(filePath);
//                if (!file.exists()){
//                    file.getParentFile().mkdirs();
//                    if (file.createNewFile()){
//                        writeAppend2(filePath,requestUrlStr);
//                    }
//                }else {
//                    if (true){
//                        writeAppend2(filePath,"\n"+requestUrlStr);
//                    }else {
//                        writeAppend2(filePath,requestUrlStr);
//                    }
//
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static void writeAppend(String fileName, byte requestUrlStr){
        FileWriter writer = null;
        try {
            writer = new FileWriter(fileName, true);
            writer.write(requestUrlStr);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
//    public static void writeAppend2(String fileName, String requestUrlStr){
//        FileWriter writer = null;
//        try {
//            writer = new FileWriter(fileName, true);
//            writer.write(requestUrlStr);
//        }catch (IOException e){
//            e.printStackTrace();
//        }finally {
//            try {
//                if(writer != null){
//                    writer.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    public static String readFileContent(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            Log.i("FileUtil",sbf.toString());
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

        return sbf.toString();
    }

//    public static List<Object> getDatFile(String fileName) throws IOException{
//        FileInputStream fis = null;
//        ObjectInputStream ois = null;
//        List<Object> list = new ArrayList<Object>();
//        Object obj = null;
//        try {
//            fis = new FileInputStream( fileName);
//            ois = new ObjectInputStream(fis);
//            while (true) {
//                try{
//                    obj = ois.readObject();
//                    list.add(obj);
//                }catch(EOFException e){
//                    break;
//                }
//            }
//        } catch (FileNotFoundException e) {
//            System.out.println("找不到指定文件" + fileName);
//            System.exit(-1);
//        }catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }finally{
//            if(ois!=null){
//                ois.close();
//            }
//            if(fis!=null){
//                fis.close();
//            }
//        }
//        Log.i("FileUtil",list.toString());
//        return list;
//    }

    /**
       * 以字节为单位读取文件，常用于读二进制文件，如图片、声音、影像等文件。
       */
    public static ByteBuffer readFileByBytes(String fileName) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024000);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容，一次读多个字节：");
            // 一次读多个字节
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            in = new FileInputStream(fileName);
            // 读入多个字节到字节数组中，byteread为一次读入的字节数
            while ((byteread = in.read(tempbytes)) != -1) {
                byteBuffer.put(tempbytes);
                //System.out.write(tempbytes, 0, byteread);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }

            }
        }
        return byteBuffer;
    }

    public static  String uploadFile(File file) throws IOException {
        String result = "fail";
        String url = "http://10.113.248.3:8085/file/uploadData";
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("multipart/form-data"),file)).build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
           result = "success";
        }else{
            System.out.println("Unexpected  code:"+response);
        }

       return result;
    }



}
